package com.me.modules.publish.controller;

import com.me.modules.common.annotation.SysLog;
import com.me.modules.common.page.Page;
import com.me.modules.common.utils.*;
import com.me.modules.publish.entity.ReleaseInfoEntity;
import com.me.modules.publish.service.ReleaseInfoService;
import com.me.modules.sys.entity.ExtendField;
import com.me.modules.sys.entity.OperationEntity;
import com.me.modules.sys.entity.ExtendFieldValue;
import com.me.modules.sys.service.ExtendFieldService;
import com.me.modules.sys.service.OperationService;
import com.me.modules.sys.service.ExtendFieldValueService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 发布工单流程
 * Created by Lenovo on 2019/1/8.
 */
@RequestMapping("/release")
@Controller
public class ReleaseController {

    @Autowired
    private ExtendFieldService extendFieldService;
    @Autowired
    private ExtendFieldValueService valueDictionaryService;
    @Autowired
    private OperationService operationService;
    @Autowired
    private ReleaseInfoService releaseInfoService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("releaseInfo:all")
    @SysLog("查看发布工单列表")
    public String list(ReleaseInfoEntity releaseInfoEntity, Model model , HttpServletRequest request){
        int pageNum = Utils.parseInt(request.getParameter("pageNum"), 1);
        Page<ReleaseInfoEntity> page = releaseInfoService.findPage(releaseInfoEntity, pageNum);

        List<ReleaseInfoEntity>  rlsList = page.getResult();
        List<ReleaseInfoEntity>  newRlsList = new ArrayList<>();
        List list =new ArrayList();
        List<ExtendField> fieldList = extendFieldService.queryByTableName("release");
        if(fieldList.size()>0){
            if( rlsList.size()>0){
                for (ReleaseInfoEntity info : rlsList) {
                    String tableId = info.getId().toString();
                    List<ExtendFieldValue> valueList = new ArrayList<>();
                    for (ExtendField fieldDictionaryEntity : fieldList) {
                        Long fieldID = fieldDictionaryEntity.getId();
                        ExtendFieldValue value=valueDictionaryService.findByFieldIdAndUserId(fieldID,tableId);
                        if(value!=null){
                            valueList.add(value);
                        }else{
                            valueList.add(new ExtendFieldValue());
                        }
                    }
                    info.setValueDictionarys(valueList);
                    newRlsList.add(info);
                }
            }
            model.addAttribute("page",new Page(newRlsList,page.getTotal(),page.getPageSize() , page.getPageNum()));

        }else{
            model.addAttribute("page",page);
        }

        model.addAttribute("release",releaseInfoEntity);
        model.addAttribute("fieldList",fieldList);

        return "release/release";


    }


    /**
     * 工单信息
     * @param model
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/info")
    @RequiresPermissions("releaseInfo:all")
    @SysLog("查看发布工单信息")
    public String info(Model model , String id, HttpServletRequest request){
        List<ExtendField> fieldList = extendFieldService.queryByTableName("release");
        if(!StringUtils.isEmpty(id)){
            ReleaseInfoEntity releaseInfo = releaseInfoService.queryObject(Long.valueOf(id));
            if(fieldList != null && fieldList.size() > 0){
                String tableId = releaseInfo.getId().toString();
                List<ExtendFieldValue> valueList = new ArrayList<>();
                for (ExtendField fieldDictionaryEntity : fieldList) {
                    Long fieldID = fieldDictionaryEntity.getId();
                    ExtendFieldValue value = valueDictionaryService.findByFieldIdAndUserId(fieldID,tableId);
                    if(value != null){
                        valueList.add(value);
                    }else{
                        valueList.add(new ExtendFieldValue());
                    }
                }
                releaseInfo.setValueDictionarys(valueList);
            }

            model.addAttribute("release",releaseInfo);
        }
        model.addAttribute("fieldList",fieldList);
        //查询业务系统
        List<OperationEntity> operationList = operationService.queryListByBean(new OperationEntity());
        model.addAttribute("operationTree", JsonUtil.getJsonByObj(operationList));
        return "release/releaseEdit";
    }


    /**
     * 新建工单/编辑工单
     * @param releaseInfoEntity
     * @return
     */
    @RequestMapping(value = "edit",method = RequestMethod.POST)
    @RequiresPermissions("releaseInfo:all")
    @ResponseBody
    public Result edit(ReleaseInfoEntity releaseInfoEntity){
        if(StringUtils.isEmpty(releaseInfoEntity.getId())){
            try {
                releaseInfoEntity.setRlsNo(Utils.getSN("RLS_","yyyyMMddHHmmss",2));
                releaseInfoEntity.setStatus("0");
                releaseInfoEntity.setReqId(UserUtils.getCurrentUser().getId());
                releaseInfoEntity.setReqName(UserUtils.getCurrentUser().getUserName());
                releaseInfoEntity.setRlsCreateDate(new Date());
                releaseInfoService.save(releaseInfoEntity);
                if(releaseInfoEntity.getValueDictionarys().size()>0) {
                    for (ExtendFieldValue value : releaseInfoEntity.getValueDictionarys()) {
                        if(!StringUtils.isEmpty(value.getFieldValue())){
                            value.setTableId(releaseInfoEntity.getId().toString());
                            valueDictionaryService.save(value);
                        }
                    }
                }
                return Result.ok("新建发布工单成功!");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("新建发布工单失败!请联系管理员");
            }
        }else {
            try {
                releaseInfoService.update(releaseInfoEntity);
                if(releaseInfoEntity.getValueDictionarys().size()>0) {
                    for (ExtendFieldValue value : releaseInfoEntity.getValueDictionarys()) {
                        ExtendFieldValue valueDictionaryEntity =
                                valueDictionaryService.findByFieldIdAndUserId(value.getFieldId(),releaseInfoEntity.getId().toString());
                        if(valueDictionaryEntity!=null){
                            valueDictionaryService.delete(valueDictionaryEntity.getId());
                        }
                        if(!StringUtils.isEmpty(value.getFieldValue())){
                            value.setTableId(releaseInfoEntity.getId().toString());
                            valueDictionaryService.save(value);
                        }
                    }
                }
                return Result.ok("修改发布工单成功!");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("修改发布工单失败!请联系管理员");
            }
        }
    }


    /**
     * 删除工单
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @RequiresPermissions("releaseInfo:all")
    @ResponseBody
    @SysLog("删除发布工单")
    public Result delete(String id){
        try {
            if(releaseInfoService.delete(Long.valueOf(id)) < 1){
                return Result.error("删除发布工单失败!请联系管理员");
            }
            return Result.ok("删除发布工单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除发布工单失败!请联系管理员");
        }
    }

}
